import React, { useEffect, useState, useRef } from "react";
import { Collapse, Input, Tabs, Button, message } from 'antd';
import { request } from 'dw-mx-request';
import './style/operationPanel.css';
import classNames from 'classnames';
import Resolution from '@/application/components/Resolution';
import ImagePicker from '@/application/components/ImagePicker';
import ApiConfig from '@/application/ApiConfig';
import MaterialUpload from '@/application/MaterialUpload';
import JavascriptEditor from '@/application/components/JavascriptEditor';
import ComponentConfig from '@/application/components/ComponentConfig';
import {useJsonStore} from '@/DragAndDrop/provider';
import {ColFlex, FlexItem} from "dw-mx-flex";
import {Select} from "dw-mx";
import {Code} from "dw-mx-extend";

export default function RightPanel(props) {

    const [jsonValue, updateJsonValue] = useState(``);

    const [apisState, setApisState] = useState([]);
    const [fileList, setFileList] = useState([]);
    const [actionUrl, setActionUrl] = useState('');

    const { Panel } = Collapse;
    const [appID, setAppID] = useState('');
    const [pageID, setPageID] = useState('');
    const [pagePropsShow, setPagePropsShow] = useState(true);
    const [componentPropsShow, setComponentPropsShow] = useState(false);
    const [pageProps,setPageProps] = useState({
        width:0,
        height:0,
        bgpic:''
    });
    const {currentComponent,changeComponentConfig,pageJson,setPageJson} = useJsonStore();

    useEffect(() => {
        setAppID(props.appid);
        setPageID(props.pageid);
        initApiConfig(props.appid, props.pageid);
        initMaterial(props.appid, props.pageid);
    }, [props.appid, props.pageid]);

    useEffect(()=>{
        ref.current = pageJson;
    },[pageJson]);
    useEffect(()=>{
        if(currentComponent && currentComponent['id'] == 'mainPage'){
            setPagePropsShow(true);
            setComponentPropsShow(false);
            setPageProps({
                ...pageProps,
                width:currentComponent['props']['designWidth'],
                height:currentComponent['props']['designHeight']
            })
        }else if(currentComponent && (currentComponent['type']['name'] == '00' || currentComponent['type']['name'] == '01')){
            const newJsonValue = currentComponent['props']['options'];
            updateJsonValue(``+JSON.stringify(newJsonValue,null, 4));
            setPagePropsShow(false);
            setComponentPropsShow(true);
        }else if(currentComponent && currentComponent['type']['name'] == 'custom'){
            const newJsonValue = currentComponent['props']['divcomponentdata'];
            updateJsonValue(``+newJsonValue);
            setPagePropsShow(false);
            setComponentPropsShow(true);
        }else if(currentComponent && (currentComponent['type']['name'] == 'rowlayout' || currentComponent['type']['name'] == 'collayout')){
            updateJsonValue(``+JSON.stringify(currentComponent['props']['style'],null, 4));
            setPagePropsShow(false);
            setComponentPropsShow(true);
        }
    },[currentComponent]);
    const initApiConfig = async (appid, pageid) => {
        const res = await request('/mx/bigScreen/initApiConfig', {
            appid: appid,
            pageid: pageid,
        });
        const result = JSON.parse(res);
        setApisState(result);
    };

    const initMaterial = async (appid, pageid) => {
        const res = await request('/mx/bigScreen/initMaterial', {
            appid: appid,
            pageid: pageid,
        });
        const result = JSON.parse(res);
        setActionUrl(result.pic_url);
        setFileList(JSON.parse(result.material));
    };

    const callback = (key) => {
        console.log(key);
    };

    const clickPageProps = () => {
        setPagePropsShow(true);
        setComponentPropsShow(false);
    };

    const clickComponentProps = () => {
        setPagePropsShow(false);
        setComponentPropsShow(true);
    };


    const changeBGImg = (val) => {
        const json = {...pageJson,
            props:{
                ...pageJson['props'],
                bgpic:val
            }
        };
        setPageJson(json);
    };

    const changeApiConfig = (val, index, key) => {
        const apiList = apisState;
        apiList[index][key] = val;
        setApisState([...apiList]);
    };

    const saveApiConfig = async (index) => {
        const para = apisState[index];
        if (para['api_name'] == undefined || para['api_name'] == '' ||
            para['api_url'] == undefined || para['api_url'] == '' ||
            para['api_interval'] == undefined || para['api_interval'] == '' ||
            para['api_mappingvariablename'] == undefined || para['api_mappingvariablename'] == '') {
            message.warn("存在未填写字段，请重新输入。");
            return;
        }
        para['appid'] = appID;
        para['pageid'] = pageID;
        const res = await request('/mx/bigScreen/saveApiConfig', para);
        const result = JSON.parse(res);
        if (result.flag == '1'){
            message.warn("返回字段名称【" + result.api_name + "】已存在，请重新输入！");
        }else {
            message.success("添加成功");
        }
        const resList = JSON.parse(result.apilist);
        setApisState([...resList]);
    };

    const deleteApiConfig = async (index) => {
        const apis = apisState;
        const api_id = apis[index]['api_id'];
        apis.splice(index, 1);
        setApisState([...apis]);
        if (api_id != undefined && api_id != ''){
            const res = await request('/mx/bigScreen/deleteApiConfig', {
                api_id: api_id,
                appid: appID,
                pageid: pageID
            });
            const result = JSON.parse(res);
            setApisState([...result]);
        }
    };

    const getChangeResolution = (width,height)=>{
        const changeJson = {...pageJson,props:{
                ...pageJson['props'],
                designHeight:height,
                designWidth:width
            }};
        setPageJson(changeJson);
    };

    const ref = useRef();
    const changeJsonValue = (value) =>{
        updateJsonValue(value);
        if(currentComponent && currentComponent['type']['name'] == 'custom'){
            const newDiv = value;
            const newComponent = {
                ...currentComponent,
                props:{
                    ...currentComponent['props'],
                    divcomponentdata:newDiv
                }
            };
            changeComponentConfig(newComponent,ref.current);
        }else if(currentComponent && (currentComponent['type']['name'] == 'normalcharts' || currentComponent['type']['name'] == 'mapcharts')){
            let newOption = currentComponent['props']['options'];
            try{
                newOption = JSON.parse(value);
            }catch(e){

            }
            const newComponent = {
                ...currentComponent,
                props:{
                    ...currentComponent['props'],
                    options:{
                        ...newOption
                    }
                }
            };
            changeComponentConfig(newComponent,ref.current);
        }else if(currentComponent && (currentComponent['type']['name'] == 'rowlayout' || currentComponent['type']['name'] == 'collayout')){
            let newStyle = currentComponent['props']['options'];
            try{
                newStyle = JSON.parse(value);
            }catch(e){

            }
            const newComponent = {
                ...currentComponent,
                props:{
                    ...currentComponent['props'],
                    style:{
                        ...newStyle
                    }
                }
            };
            changeComponentConfig(newComponent,ref.current);
        }
    };

    const layoutChange = (value,options) =>{
        console.log(value,options);
    };

    return (
        <div style={{height:"95%"}} className={classNames('dlc-rp', {
            'dlc-rp-page-show': pagePropsShow,
            'dlc-rp-component-show': componentPropsShow
        })}>
            <Button className={'dlc-rp-btn'} onClick={()=>clickPageProps()}>页面属性</Button>
            <Button className={'dlc-rp-btn'} onClick={()=>clickComponentProps()}>组件属性</Button>
            <div className={'dlc-rp-page'}>
                <Collapse defaultActiveKey={['']} onChange={(val)=>callback(val)}>
                    <Panel header="分辨率" key={appID + pageID + '01'}>
                        <Resolution width={pageProps['width']} height={pageProps['height']} changeResolution={getChangeResolution}/>
                    </Panel>
                    <Panel header="整体布局" key={appID + pageID + '05'}>
                        <Select onChange={layoutChange} defaultValue={'collayout'} options={Code.STRINGCODE('rowlayout:横向布局,collayout:纵向布局')} placeholder={'请选择...'} />
                    </Panel>
                    <Panel header="背景图" key={appID + pageID + '02'}>
                        <ImagePicker value={pageProps['bgpic']} appid={appID} pageid={pageID} changeValue={(val)=>changeBGImg(val)}/>
                    </Panel>
                    <Panel header="数据配置" key={appID + pageID + '03'}>
                        <ApiConfig apis={apisState}
                                   onSave={(index) => {
                                       saveApiConfig(index)
                                   }}
                                   onChange={(val, index, key)=>changeApiConfig(val, index, key)}
                                   onDelete={(index, apis) => deleteApiConfig(index)}
                                   onAdd={(apis) => {
                                       apis.push({});
                                       setApisState([...apis]);
                                   }}/>
                    </Panel>
                    <Panel header="页面素材" key={appID + pageID + '04'}>
                        <MaterialUpload fileList={fileList} actionUrl={actionUrl}/>
                    </Panel>
                </Collapse>
            </div>
            <div className={'dlc-rp-component'}>
                <ColFlex>
                    <FlexItem flexBasic={150}>
                        <ComponentConfig/>
                    </FlexItem>
                    <FlexItem>
                        <JavascriptEditor value={jsonValue} onChange={(value) => changeJsonValue(value)} />
                    </FlexItem>
                </ColFlex>
                {/*<div style={{ display: "flex",height:'100%' }}>*/}
                    {/*<div style={{ flex: "1 1 0px" }}>*/}
                        {/*<JavascriptEditor value={jsonValue} onChange={(value) => changeJsonValue(value)} />*/}
                    {/*</div>*/}
                {/*</div>*/}
            </div>
        </div>
    );
}